<template>
  <el-dialog v-model="userVisible" title="新建用户" width="500" @close="resetForm(userFormRef)">
    <el-form ref="userFormRef" :model="userForm" :rules="rules" label-width="80px">
      <el-form-item prop="username" label="用户名">
        <el-input
          v-model="userForm.username"
          placeholder="请输入用户名"
          :disabled="mode === 1"
        ></el-input>
      </el-form-item>
      <template v-if="mode === 0">
        <el-form-item prop="password" label="密码">
          <el-input
            v-model="userForm.password"
            placeholder="请输入密码  (6~16)位"
            type="password"
            @paste.prevent="() => {}"
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirm" label="确认密码">
          <el-input
            v-model="userForm.confirm"
            placeholder="请确认密码"
            type="password"
            @paste.prevent="() => {}"
          ></el-input>
        </el-form-item>
      </template>
      <el-form-item prop="role" label="身份">
        <el-select v-model="userForm.role" style="width: 240px">
          <template v-for="key in roles" :key="key">
            <el-option
              v-if="isNaN(key) && (roles[key] as unknown as number) !== 0"
              :label="key"
              :value="roles[key]"
            />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item prop="remark" label="备注">
        <el-input v-model="userForm.remark" placeholder="请确认备注信息"></el-input>
      </el-form-item>
      <el-form-item prop="avatar" label="头像">
        <MyPicUpload ref="MyPicUploadRef" size="120px" :limit="1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userVisible = false">取消</el-button>
        <el-button type="primary" @click="userSubmit(userFormRef)" :loading="loading">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { UserForm } from '@/types/user'
import type { FormInstance, FormRules } from 'element-plus'
import { roles } from '@/utils/enum'
import { ref, reactive, computed, watch } from 'vue'
import { createUserApi, updateUserApi } from '@/api/user'
import MyPicUpload from '@/components/MyPicUpload.vue'

const userVisible = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val)
  }
})

type Props = {
  visible: boolean
  mode: number
  user_id: number
  form: UserForm
}

const props = defineProps<Props>()

const emits = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'getUserList', scroll?: boolean): void
}>()

const userFormRef = ref<FormInstance>() // user表单组件实例
const MyPicUploadRef = ref<InstanceType<typeof MyPicUpload>>() // 文件上传组件实例

const loading = ref(false)

//  表单数据
const userForm = reactive<UserForm>({
  username: '',
  password: '',
  confirm: '',
  avatar: '',
  remark: '',
  role: 2
})

//  自定义验证二次输入密码
const checkConfirm = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password again'))
  } else if (value !== userForm.password) {
    callback(new Error("Two inputs don't match!"))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<UserForm>>({
  username: [{ required: true, message: 'Please input username', trigger: 'blur' }],
  password: [
    { required: true, message: 'Please input password', trigger: 'blur' },
    {
      min: 6,
      max: 16,
      message: 'Length should be 6 to 16',
      trigger: 'blur'
    }
  ],
  confirm: [{ required: true, validator: checkConfirm, trigger: 'blur' }]
})

const userSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      // 获取子组件文件数据
      if (MyPicUploadRef.value?.fileList.length) {
        // raw 新建时上传的图片文件
        // url 编辑时用户原本的图片路径
        const { raw, url } = MyPicUploadRef.value.fileList[0]
        userForm.avatar = raw || url?.substring(4)
      } else {
        userForm.avatar = ''
      }
      let formData = new FormData()
      for (const [key, val] of Object.entries(userForm)) {
        val ? formData.append(key, val as any) : null
      }
      try {
        if (props.mode === 0) {
          await createUserApi(formData)
          loading.value = false
          userVisible.value = false
          emits('getUserList')
        } else {
          await updateUserApi(props.user_id, formData)
          loading.value = false
          userVisible.value = false
          emits('getUserList', false)
        }
      } catch (error) {
        loading.value = false
      }
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  //  清空子组件文件
  MyPicUploadRef.value!.fileList = []
}

watch(
  () => props.form,
  (n) => {
    const { avatar } = n
    Object.assign(userForm, n)
    avatar
      ? MyPicUploadRef.value?.fileList.push({
          name: '',
          url: '/api' + avatar
        })
      : null
  },
  {
    deep: true
  }
)
</script>

<style scoped></style>
